const util = require('../../utils/util.js');
import server from "../../utils/server";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    active2: 2,
    originalList: [], // 原始未审核列表备份
    originalList2: [], // 原始已通过列表备份
    originalList3: [], // 原始未通过列表备份
    searchKeyword: '', // 保存当前搜索关键词
    selectedIds: [],
    list: [],
    list2: [],
    list3: [],
    value: '',
    show2: false,
    show3: false,
    show4:false,
    show5:false,
    showConfirmDialog: false,
    currentRejectReason: '',
    FullBrand:'',
    Fullmedium:'',
    statusBarHeight: 0, // 状态栏高度
    menuButtonHeight: 0, // 胶囊按钮高度（用于导航栏内容区）
    navHeight: 0,
    currentList: [], // 动态数据源（根据active切换）
    currentImage: '',
    hasMore: true,      // 是否还有更多数据
    loading: false,
    pageNum: 1,         // 当前页码
    pageSize: 5,
    mediaPartyId:null,
    auditchecked:[],
    sysValuelist:[]
  },

  getIntendedMediaListfun(isLoadMore = false) {
    // 如果正在加载或没有更多数据，直接返回
    if (this.data.loading || (!isLoadMore && this.data.pageNum > 1) || !this.data.hasMore) {
      return;
    }
  
    this.setData({ loading: true });
  
    let params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      status: 1, // 默认未审核
      mediaPartyId:this.data.mediaPartyId
    };
  
    if (this.data.active === 1 && this.data.active2 == 2) {
      params.status = 2; // 已通过
    } else if (this.data.active === 1 && this.data.active2 == 3) {
      params.status = 3; // 未通过
    }
  
    if (this.data.searchKeyword !== '') {
      params.keyword = this.data.searchKeyword;
    }
  
    server.post('/app/user/getIntendedMediaList', params)
      .then(res => {
        this.setData({ loading: false });
        if (res.key === 1000) {
          const formattedList = this.formatListTime(res.result.list).map(item => ({
            ...item,
            mediaList: item.mediaList.map(medium => ({
              ...medium,
              checked: false // 初始未选中
            }))
          }));
  
          let originalKey = '';
          if (params.status === 1) {
            originalKey = 'originalList';
          } else if (params.status === 2) {
            originalKey = 'originalList2';
          } else if (params.status === 3) {
            originalKey = 'originalList3';
          }
  
          // 处理加载更多逻辑：是追加还是替换
          let syncedList = formattedList;
          if (isLoadMore && this.data[originalKey] && this.data[originalKey].length > 0) {
            // 加载更多时合并数据
            syncedList = [...this.data[originalKey], ...formattedList];
          } else if (this.data[originalKey] && this.data[originalKey].length > 0) {
            // 非加载更多时同步选中状态
            syncedList = this.syncCheckStatus(formattedList, this.data[originalKey]);
          }
  
          // 判断是否还有更多数据
          const hasMore = formattedList.length >= this.data.pageSize;
  
          const updateData = {
            [originalKey]: syncedList,
            hasMore,
            loading: false
          };
  
          // 更新当前列表
          if (
            (params.status === 1 && this.data.active === 0) ||
            (params.status === 2 && this.data.active === 1 && this.data.active2 == 2) ||
            (params.status === 3 && this.data.active === 1 && this.data.active2 == 3)
          ) {
            updateData.currentList = isLoadMore ? [...this.data.currentList, ...formattedList] : syncedList;
          }
  
          this.setData(updateData);
        }
      })
      .catch(err => {
        this.setData({ loading: false });
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      });
  },

  getSysLabelValueManageListfun(){
let params = {
  sysLabelIds:60
}
server.post('/app/user/getSysLabelValueManageList',params).then(res=>{
  if(res.key == 1000){
    this.setData({
      sysValuelist:res.result.data[60]
    })
  }

  console.log(this.data.sysValuelist,123)
})
  },

  onChange(e) {
    const newActive = e.detail.name;
    // 保存当前列表的选中状态到对应原始列表
    if (this.data.active === 0) {
      this.setData({ originalList: JSON.parse(JSON.stringify(this.data.currentList)) });
    } else if (this.data.active === 1 && this.data.active2 == 2) {
      this.setData({ originalList2: JSON.parse(JSON.stringify(this.data.currentList)) });
    } else if (this.data.active === 1 && this.data.active2 == 3) {
      this.setData({ originalList3: JSON.parse(JSON.stringify(this.data.currentList)) });
    }
    this.setData({ 
      active: newActive, 
      searchKeyword: '',
      pageNum: 1,
      hasMore: true
    }, () => {
      this.getIntendedMediaListfun();
    });
    // 如果有搜索关键词，切换标签后重新执行搜索
    // if (this.data.searchKeyword) {
    //   // 手动触发搜索逻辑
    //   const event = { detail: this.data.searchKeyword };
    //   this.onSearch(event);
    // } else {
    //   ;
    // }
  },

  onChange3(e) {
    const newActive2 = e.detail.name;
    // 1. 保存当前列表的选中状态到对应原始列表（与主标签逻辑一致）
    if (this.data.active === 1 && this.data.active2 == 2) {
      this.setData({ originalList2: JSON.parse(JSON.stringify(this.data.currentList)) });
    } else if (this.data.active === 1 && this.data.active2 == 3) {
      this.setData({ originalList3: JSON.parse(JSON.stringify(this.data.currentList)) });
    }
    // 2. 先更新子标签状态（确保接口请求使用最新的active2）
    this.setData({ 
      active2: newActive2,
      searchKeyword: '',
      pageNum: 1,
      hasMore: true
    }, () => {
      this.getIntendedMediaListfun();
    });
  },

  onSearch(e) {
    const keyword = e.detail.trim().toLowerCase();
    this.setData({
      searchKeyword: keyword
    });
  
    // 根据当前激活的标签页选择对应的原始数据
    let originalData;
    if (this.data.active === 0) {
      originalData = this.data.originalList;
    } else if (this.data.active2 === 2) {
      originalData = this.data.originalList2;
    } else {
      originalData = this.data.originalList3;
    }
    // 过滤数据并保留选择状态
    let filteredData;
    if (keyword) {
      filteredData = originalData.filter(item => {
        // 检查品牌名是否匹配（使用实际展示的 brandPlacement 字段）
        const brandMatch = item.brandPlacement.toLowerCase().includes(keyword);
        // 检查媒体名称是否匹配（使用实际展示的 mediaName 字段）
        const mediumMatch = item.mediaList.some(medium =>
          medium.mediaName.toLowerCase().includes(keyword)
        );
        // 增加对驳回理由的搜索支持
        const rejectReasonMatch = item.mediaList.some(medium =>
          medium.auditReason  && medium.auditReason .toLowerCase().includes(keyword)
        );
         // 检查提交时间是否匹配
      const createTimeMatch = item.mediaList.some(medium =>
        medium.createTime.toLowerCase().includes(keyword)
      );
         
        return brandMatch || mediumMatch || rejectReasonMatch || createTimeMatch;
      });
    } else {
      // 如果关键词为空，显示全部数据
      filteredData = JSON.parse(JSON.stringify(originalData));
    }
    
    // 同步勾选状态
    filteredData = this.syncCheckStatus(filteredData, this.data.currentList);
    
    this.setData({
      currentList: filteredData
    });
  },

  // 全选状态变化处理
onAllCheckChange(e) {
  const { itemIndex } = e.currentTarget.dataset;
  const isChecked = e.detail;
  const currentList = [...this.data.currentList];
  
  // 更新当前组的全选状态
  currentList[itemIndex].allChecked = isChecked;
  
  // 更新组内所有媒体项的选中状态
  currentList[itemIndex].mediaList = currentList[itemIndex].mediaList.map(medium => ({
    ...medium,
    checked: isChecked
  }));
  
  // 更新对应原始列表的状态
  this.updateOriginalList(currentList);
  
  this.setData({
    currentList
  });
},

  //工具方法：时间戳转换
  formatListTime(list) {
    return list.map(item => {
      //const itemCheckTimeFormatted = util.formatTime2(new Date(Number(item.checkTime)));
      let itemCheckTimeFormatted = '';
      if (item.checkTime !== null && item.checkTime !== undefined) {
        const checkTimeNum = Number(item.checkTime);
        // 只有当是有效数字且大于0时才格式化
        if (!isNaN(checkTimeNum) && checkTimeNum > 0) {
          itemCheckTimeFormatted = util.formatTime2(new Date(checkTimeNum));
        }
      }
      // 2. 格式化 mediaList 中每个 medium 的时间字段
      const formattedMediaList = item.mediaList ? item.mediaList.map(medium => {
        const mediumCreateTimeFormatted = util.formatTime2(new Date(Number(medium.createTime)));
        const mediumAuditTimeFormatted = util.formatTime2(new Date(Number(medium.auditTime)));
        return {
          ...medium,
          createTime: mediumCreateTimeFormatted, // 媒体项的提交时间格式化
          auditTime: mediumAuditTimeFormatted // 媒体项的审核时间格式化
        };
      }) : [];

      // 3. 返回完整格式化后的 item
      return {
        ...item,
        checkTime: itemCheckTimeFormatted,
        mediaList: formattedMediaList, // 替换为格式化后的媒体列表
        allChecked: false 
      };
    });
  },

  // 同步勾选状态的工具方法
  syncCheckStatus(targetList, sourceList) {
    const result = JSON.parse(JSON.stringify(targetList));
    const sourceMap = {};
    
    sourceList.forEach(item => {
      sourceMap[item.projectId] = {
        allChecked: item.allChecked,  // 同步全选状态
        mediaMap: {}
      };
      item.mediaList.forEach(medium => {
        sourceMap[item.projectId].mediaMap[medium.intendedMediaId] = medium.checked;
      });
    });
  
    result.forEach(targetItem => {
      if (sourceMap[targetItem.projectId]) {
        // 同步全选状态
        targetItem.allChecked = sourceMap[targetItem.projectId].allChecked;
        
        // 同步单个项状态
        targetItem.mediaList.forEach(medium => {
          if (sourceMap[targetItem.projectId].mediaMap[medium.intendedMediaId] !== undefined) {
            medium.checked = sourceMap[targetItem.projectId].mediaMap[medium.intendedMediaId];
          }
        });
      }
    });
    return result;
  },


  handlereject(e) {
    // 获取当前点击的列表项索引和媒体项索引
    const {
      itemIndex,
      index: mediumIndex
    } = e.currentTarget.dataset;
    this.setData({
      currentItemIndex: itemIndex,
      currentMediumIndex: mediumIndex,
      show2: true,
      value: '',
      auditchecked:[]
    });
  },
  rejectview(e) {
    const reason = e.currentTarget.dataset.reason || '无驳回理由';
    this.setData({
      show3: true,
      currentRejectReason: reason // 设置当前要显示的理由
    });
  },
  showFullBrand(e){
    const brand = e.currentTarget.dataset.brand || '-';
    this.setData({
      show4: true,
      FullBrand: brand
    });
  },
  showFullmedium(e){
    const medium = e.currentTarget.dataset.medium;
    console.log(e)
    this.setData({
      show5: true,
      Fullmedium: medium
    });
  },
imageview(e) {
  const imageUrl = e.currentTarget.dataset.item;
  if (!imageUrl) return;
  wx.previewImage({
    current: imageUrl, // 当前显示图片的http链接
    urls: [imageUrl],  // 需要预览的图片http链接列表（支持多张）
    showmenu: true,    // 允许长按菜单显示
    fail: (err) => {
      console.error('图片预览失败', err);
      wx.showToast({
        title: '图片加载失败',
        icon: 'none'
      });
    }
  });
},

  onChange2(e) {
    const { itemIndex, mediumIndex } = e.currentTarget.dataset;
    const isChecked = e.detail;
    const currentList = [...this.data.currentList];
    
    // 更新单个媒体项的选中状态
    currentList[itemIndex].mediaList[mediumIndex].checked = isChecked;
    
    // 检查是否所有媒体项都被选中
    const allChecked = currentList[itemIndex].mediaList.every(medium => medium.checked);
    currentList[itemIndex].allChecked = allChecked;
    
    // 更新对应原始列表的状态
    this.updateOriginalList(currentList);
    
    this.setData({
      currentList
    });
  },

  // 新增辅助方法：更新原始列表状态
updateOriginalList(currentList) {
  let originalKey;
  if (this.data.active === 0) {
    originalKey = 'originalList';
  } else if (this.data.active2 === 2) {
    originalKey = 'originalList2';
  } else {
    originalKey = 'originalList3';
  }
  
  this.setData({
    [originalKey]: JSON.parse(JSON.stringify(currentList))
  });
},


  handconfirm() {
    const selectedIds = [];
    // 遍历当前列表
    this.data.currentList.forEach(item => {
      // 遍历每个品牌下的媒体项
      item.mediaList.forEach(medium => {
        // 收集选中项的id
        if (medium.checked) {
          selectedIds.push(medium.intendedMediaId);
        }
      });
    });
    if (selectedIds.length === 0) {
      wx.showToast({
        title: '请先选择媒体',
        icon: 'none'
      });
      return;
    }
    this.setData({
      showConfirmDialog: true,
      selectedIds: selectedIds // 存储到data中
    })
  },

  batchReject(){
 // 收集所有选中的媒体项
 const selectedItems = [];
 this.data.currentList.forEach((item, itemIndex) => {
   item.mediaList.forEach((medium, mediumIndex) => {
     if (medium.checked) {
       selectedItems.push({
         ...medium,
         itemIndex,
         mediumIndex
       });
     }
   });
 });

 if (selectedItems.length === 0) {
   wx.showToast({
     title: '请先选择需要驳回的媒体',
     icon: 'none'
   });
   return;
 }

 // 保存选中的项并显示驳回理由输入框
 this.setData({
   batchSelectedItems: selectedItems,
   value: '', // 清空之前的输入
   show2: true, // 显示驳回弹窗
   auditchecked: []
 });
},

// 修改原有的rejectConfirm方法以支持批量处理
rejectConfirm() {
 const reason = this.data.value || '未说明理由';
 
 // 判断是批量驳回还是单个驳回
 if (this.data.batchSelectedItems && this.data.batchSelectedItems.length > 0) {
   // 批量驳回处理
   const ids = this.data.batchSelectedItems.map(item => item.intendedMediaId);
   
   let params = {
    id:ids.join(','),
    auditReason: reason
   }
   server.post('/app/user/doRejectIntendedMedia',params).then(res => {
     if (res.key === 1000) {
       wx.showToast({
         title: '批量驳回成功',
         icon: 'success'
       });
       
       // 更新本地列表状态
       let newCurrentList = [...this.data.currentList];
         // 获取当前时间戳（毫秒级，用于格式化）
         const currentTimeStamp = util.formatTime2(new Date());
       this.data.batchSelectedItems.forEach(({itemIndex, mediumIndex}) => {
         newCurrentList[itemIndex].mediaList[mediumIndex].status = 3;
         newCurrentList[itemIndex].mediaList[mediumIndex].checked = false;
         newCurrentList[itemIndex].mediaList[mediumIndex].auditReason = reason;
         newCurrentList[itemIndex].mediaList[mediumIndex].auditTime = currentTimeStamp;
       });
       
       this.setData({
         currentList: newCurrentList,
         originalList: JSON.parse(JSON.stringify(newCurrentList)),
         show2: false,
         batchSelectedItems: []
       });
     }
   }).catch(err => {
     wx.showToast({
       title: '操作失败',
       icon: 'none'
     });
   });
 } else {
    const {
      currentItemIndex,
      currentMediumIndex,
      value,
      currentList
    } = this.data;
    const newList = JSON.parse(JSON.stringify(currentList));
    const currentTime = util.formatTime2(new Date());
    const intendedMediaId = newList[currentItemIndex].mediaList[currentMediumIndex].intendedMediaId;
    let params = {
      auditReason: value,
      id: intendedMediaId
    }
    server.post('/app/user/doRejectIntendedMedia', params)
      .then(res => {
        if (res.key == 1000) {
          newList[currentItemIndex].mediaList[currentMediumIndex].auditReason = value;
          newList[currentItemIndex].mediaList[currentMediumIndex].auditTime = currentTime;
          newList[currentItemIndex].mediaList[currentMediumIndex].status = 3
          this.setData({
            value: "", // 清空全局输入框
            show2: false,
            currentList: newList
          });
          wx.showToast({
            title: res.message,
            icon: 'none',
          });
        }
      })
 }
  },

  // 二次确认弹窗：用户点击“确定”
  onConfirm() {
    const {
      selectedIds,
      currentList
    } = this.data;
    const newList = JSON.parse(JSON.stringify(currentList));
    const currentTime = util.formatTime2(new Date());
    let params = {
      ids: selectedIds.join(',')
    };
    server.post('/app/user/doAcceptIntendedMedia', params).then(res => {
      if (res.key == 1000) {
       // this.getIntendedMediaListfun();
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
    // 隐藏弹窗
    this.setData({ 
      showConfirmDialog: false,
      searchKeyword: '',
      pageNum: 1,
      hasMore: true
    }, () => {
      this.getIntendedMediaListfun();
    });
  },

  // 二次确认弹窗：用户点击“取消”
  onCancel() {
    // 隐藏弹窗
    this.setData({
      showConfirmDialog: false
    });
    console.log('用户取消提交');
  },

  auditChange(e) {
    const selectedIds = e.detail; 
    const { sysValuelist } = this.data; 
  
    // 将 selectedIds 中的每一项转为数字
    const numericSelectedIds = selectedIds.map(id => Number(id));
  
    // 筛选出选中的选项名称（使用转换后的数字数组匹配）
    const selectedNames = sysValuelist
      .filter(item => numericSelectedIds.includes(item.id)) 
      .map(item => item.sysValueName);
  
    // 将选中的名称用分号拼接，并更新到文本框
    this.setData({
      auditchecked: selectedIds, 
      value: selectedNames.join(';') 
    });   
  },

  copyprojectName(e){
    console.log(e.currentTarget.dataset.brand)
    wx.setClipboardData({
      data: e.currentTarget.dataset.brand,
      success (res) {
        console.log(res)
        // wx.getClipboardData({
        //   success (res) {
        //     console.log(res.data) // data
        //   }
        // })
      }
    })
  },


  noop(){
    //阻止事件冒泡
  },

  //重新选择意向媒体方
  choosemedium(){
    wx.navigateBack();
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options.id)
    const formattedList = this.formatListTime(this.data.list);
    const formattedList2 = this.formatListTime(this.data.list2);
    const formattedList3 = this.formatListTime(this.data.list3);
    // 获取系统信息，计算导航栏高度
    const systemInfo = wx.getSystemInfoSync();
    // 获取胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 状态栏高度
    const statusBarHeight = systemInfo.statusBarHeight;
    // 导航内容区高度（使用胶囊按钮的高度）
    const menuButtonHeight = menuButtonInfo.height + 10;
    // 整个导航栏高度 = 状态栏高度 + 胶囊按钮高度
    const navHeight = statusBarHeight + menuButtonHeight + 10;
    const id = options.id;
    if(id){
      this.setData({
        mediaPartyId : Number(id)
      })
    }
    this.getIntendedMediaListfun();
    this.getSysLabelValueManageListfun();
    // 设置数据
    this.setData({
      statusBarHeight,
      menuButtonHeight,
      navHeight,
      list: formattedList,
      list2: formattedList2,
      list3: formattedList3,
      originalList: JSON.parse(JSON.stringify(formattedList)), // 深拷贝保存原始数据
      originalList2: JSON.parse(JSON.stringify(formattedList2)),
      originalList3: JSON.parse(JSON.stringify(formattedList3)),
      currentList: formattedList, // 初始显示未审核数据
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showToast({
      title: '刷新中...',
      icon:'none'
    })
    this.setData({ 
      searchKeyword: '',
      pageNum: 1,
      hasMore: true
    }, () => {
      this.getIntendedMediaListfun();
       wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
     // 如果还有更多数据且不在加载中，加载下一页
  if (this.data.hasMore && !this.data.loading) {
    this.setData({
      pageNum: this.data.pageNum + 1
    }, () => {
      this.getIntendedMediaListfun(true); // 传入true表示加载更多
    });
  }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})